package com.wyb.service.impl;

import com.wyb.mapper.CommentMapper;
import com.wyb.mapper.UserMapper;
import com.wyb.pojo.Comment;
import com.wyb.constant.Result;
import com.wyb.pojo.User;
import com.wyb.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result getComment(int topicId) {

        List<Comment> comments = commentMapper.selectByTopicId(topicId);
        return getResult(comments,"评论");
    }

    @Override
    public Result getReply(int id) {
        List<Comment> comments = commentMapper.selectReplyByParentId(id);
        return getResult(comments,"回复");
    }

    //获取评论或回复
    private Result getResult(List<Comment> comments, String msg){

        if (!comments.isEmpty()) {
            List<Map<String, Object>> maps = new ArrayList<>();
            int count = 0;
            for (Comment comment : comments) {
                count++;
                Map<String, Object> stringObjectMap = new HashMap<>();
                User user = userMapper.selectById(comment.getUserId());
                User user1;
                User user2;
                List<Comment> comments1 = commentMapper.selectReplyByParentId(comment.getId());
                int size = comments1.size();
                stringObjectMap.put("avatar", user.getAvatar());
                stringObjectMap.put("nickName", user.getNickName());
                stringObjectMap.put("comment", comment);
                stringObjectMap.put("size", size);
                if (comment.getReplyUserId()!= null) {
                    Long userId = commentMapper.selectUserIdByReplyUserId(comment.getReplyUserId());
                    user2 = userMapper.selectById(userId);
                    if(!Objects.isNull(user2)){
                        stringObjectMap.put("replyNickName",user2.getNickName());
                    }
                }
                maps.add(stringObjectMap);
            }
            return new Result(200, "共"+count+"条"+msg, maps);
        } else {
            return new Result(201, "共0条"+msg, null);
        }
    }
}
